#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <netinet/ip.h>

#include <arpa/inet.h>

#define SERV_PORT 9783
#define BUFFER 1024

int main(int argc, char ** argv) {
  int sockfd;
  struct sockaddr_in servaddr, cliaddr;
  
  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sockfd == -1) {
    printf("ERROR: Could not create a socket.\n");
    return 1;
  }

  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(SERV_PORT);
  
  if (bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1) {
    printf("ERROR: Could not bind the network socket.\n");
    close(sockfd);
    return 1;
  }
  
  int n;
  socklen_t len;
  char mesg[BUFFER];

  for (;;) {
    len = sizeof(cliaddr);
    n = recvfrom(sockfd, mesg, BUFFER, 0, (struct sockaddr*)&cliaddr, &len);
    if (len > 0) {
      mesg[n] = 0;
      sendto(sockfd, mesg, n, 0, (struct sockaddr*)&cliaddr, len);
    } else {
      printf("ERROR: Failed to receive from host.\n");
    }
  }

  close(sockfd);
  return 0;
}
